<template>
  <div class="app-container">
    <SettlementAuditFilter :commSeleList="commSeleList"
                           :commCaseSeleList="commCaseSeleList"
                           @on-filter="submitFilterForm"
                           @on-export="exportHandle"
                           :downLoading="downloadLoading" />
    <div style="padding: 20px 0">
      <el-button-group>
        <el-button v-if="roleCheck('batch-audit')"
                   size="mini"
                   type="primary"
                   @click="multipAudit">批量审核</el-button>
      </el-button-group>
    </div>
    <el-table :data="tableData.list"
              border
              @selection-change="handleSelectionChange"
              v-loading="loading"
              element-loading-text="加载中...">
      <el-table-column type="selection"
                       :selectable="isSelectable"
                       align="center"
                       width="55"></el-table-column>
      <el-table-column prop="settleDate"
                       label="结算月份"
                       align="center"></el-table-column>
      <el-table-column label="代理账号"
                       prop="username"
                       align="center"></el-table-column>
      <el-table-column label="姓名"
                       prop="name"
                       align="center"></el-table-column>
      <el-table-column label="账号状态"
                       align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.userStatus === 2" type="warning">间接锁定</el-tag>
          <el-tag v-else-if="row.userStatus === 3 " type="info">审核中</el-tag>
          <el-tag v-else-if="row.userStatus === 1 " type="danger">完全锁定</el-tag>
          <el-tag v-else-if="row.userStatus === -1|| row.userStatus === 0" type="success">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="手续费方案(本月)"
                       prop="feeRule"
                       align="center">
        <template slot-scope="{row}">
          {{formatFeeRuleName(row)}}
        </template>
      </el-table-column>
      <el-table-column label="佣金方案类型"
                       prop="commName"
                       align="center">
        <template slot-scope="{row}">
          {{formatCommMode(row.commMode).name}}
        </template>
      </el-table-column>
      <el-table-column label="会员反佣方案(现金网)"
                       prop="cashRule"
                       align="center">
        <template slot-scope="{row}">
          <div v-if="row.commMode == 1">{{formatCashRuleName(row)}}</div>
          <div v-else>--</div>
        </template>
      </el-table-column>
      <el-table-column label="有效会员"
                       prop="userCount"
                       align="center"></el-table-column>
      <el-table-column label="有效下级代理总数"
                       prop="proxyCount"
                       align="center"></el-table-column>
      <el-table-column label="公司总输赢"
                       prop="platformComm"
                       align="center">
        <template slot-scope="{row}">
          <el-button @click="openDialog({props:row,dialogName:staticDialogName2})"
                     type="text">
            {{row.winTotal | currency}}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="成本总计"
                       prop="cost"
                       align="center">
        <template slot-scope="{row}">
          <el-button @click="openDialog({props:row,dialogName:staticDialogName3})"
                     type="text">
            {{row.cost | currency}}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="累加上月"
                       prop="lastAmount"
                       width="150"
                       align="center">
        <template slot-scope="{row}">
          <el-tag type="danger">{{row.lastAmount | currency}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="下级会员佣金"
                       prop="commAmount"
                       align="center">
        <template slot-scope="{row}">
          <el-button type="text"
                     @click="openDialog({props:row,dialogName:staticDialogName8})">{{row.commAmount | currency}}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="下级代理佣金"
                       prop="proxyComm"
                       align="center">
        <template slot-scope="{row}">
          <el-button @click="openDialog({props:row,dialogName:staticDialogName6})"
                     type="text">{{row.proxyComm | currency}}
          </el-button>
        </template>
      </el-table-column>
      <!-- <el-table-column label="上分返利"
                       prop="upAmountRet"
                       align="center">
        <template slot-scope="{row}">
          <el-button @click="openDialog({props:row,dialogName:staticDialogName9})"
                     type="text">{{row.upAmountRet | currency}}
          </el-button>
        </template>
      </el-table-column> -->
      <!--</el-table-column>-->
      <el-table-column label="实际合计发放"
                       prop="amount"
                       align="center">
        <template slot-scope="{row}">
          {{row.amount | currency}}
        </template>
      </el-table-column>
      <el-table-column label="结算状态"
                       fixed="right"
                       prop="status"
                       align="center"
                       width="100">
        <template slot-scope="{row}">
          <el-button type="text"
                     v-if="row.status === 0 && roleCheck('first-audit')"
                     @click="showAuditDialog(row,1)">
            待初审
          </el-button>
          <el-button type="text"
                     v-else-if="row.status === 1 && roleCheck('second-audit')"
                     @click="showAuditDialog(row,2)">
            初审通过
          </el-button>
          <div v-else>{{agencyEnum.AUDIT_REVIEW_TYPE[row.status]}}</div>
        </template>
      </el-table-column>
      <el-table-column label="时间"
                       fixed="right"
                       prop="firstTime"
                       align="center"
                       width="160">
        <template slot-scope="{row}">
          {{row.firstTime | toTime}}
        </template>
      </el-table-column>
      <el-table-column label="审核人"
                       fixed="right"
                       prop="firstApprover"
                       align="center"
                       width="100">
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background
                     @size-change="gridSizeChange"
                     @current-change="gridCurrentChange"
                     :current-page="filters.page"
                     :page-sizes="gridPageSize"
                     :page-size="filters.size"
                     :layout="gridLayout"
                     :total="tableData.total">
      </el-pagination>
    </div>
    <el-tip style="padding: 50px 0 10px 0;">
      <p> 注1：“公司总输赢”红色负数代表会员盈利，绿色正数代表公司盈利</p>
      <p> 注2:【公司总输赢】投注金额-派彩金额</p>
      <p>　 【成本总计】{（游戏输赢*平台费）"公司输则平台费用为0"}+红利+返水+存提款手续费</p>
      <p> 　 【累加上月】上月公司总输赢-成本总计</p>
      <p> 　 【公司净输赢】公司总输赢-成本总计 </p>
      <p> 　 【下级会员佣金】（公司净输赢+累加上月）*佣金比例 </p>
      <p> 　 【下级代理佣金】下级代理佣金总额*提成比例</p>
      <p> 　 【实际发放】当下级会员佣金为负数的时候，实际发放金额=下级代理佣金+上分返利</p>
      <p> 　 当下级会员佣金为正数的时候，实际发放金额=下级会员佣金+下级代理佣金+上分返利</p>
      <p> 注3: 代理佣金数据每个小时，会定时结算一次最新的数值。每个月5号凌晨3点，统一结算上个月的佣金，结算后无法再次更改 </p>
    </el-tip>
    <CommissionAuditDialog v-if="dialogName === staticDialogName"
                           v-model="dialogVisible"
                           :status="dialogProps.auditStatus"
                           :id="dialogProps.id"
                           :step="auditStep"
                           @submit="submitFinished" />
    <CommissionAuditViewDialog v-if="dialogName === staticDialogName5"
                               v-model="dialogVisible"
                               :row-data="dialogProps"
                               :step="auditStep"
                               @submit="submitFinished" />
    <GameCommissionDialog v-if="dialogName === staticDialogName2"
                          v-model="dialogVisible"
                          :id="dialogProps.id"
                          @submit="submitFinished" />

    <ApportionCommissionDialog v-if="dialogName === staticDialogName3"
                               v-model="dialogVisible"
                               :id="dialogProps.id"
                               @submit="submitFinished" />

    <AdjustCommissionDialog v-if="dialogName === staticDialogName4"
                            v-model="dialogVisible"
                            :id="dialogProps.id"
                            @submit="submitFinished" />
    <SubCommissionDialog v-if="dialogName === staticDialogName6"
                         v-model="dialogVisible"
                         :id="dialogProps.id"
                         @submit="submitFinished" />
    <MultiplyAuditDialog v-if="dialogName === staticDialogName7"
                         v-model="dialogVisible"
                         :ids="idsArr"
                         @submit="submitFinished" />
    <NextMemberCommissionDialog v-if="dialogName === staticDialogName8"
                                v-model="dialogVisible"
                                :detail="dialogProps" />
    <AddPointsRebate v-if="dialogName === staticDialogName9"
                     v-model="dialogVisible"
                     :detail="dialogProps" />
  </div>
</template>

<script>

// constants
import agencyEnum, { FILTER_ALL_TYPE } from '@/const/agencyEnum';

// utils
import { formatCommMode, mapToArray } from '@/utils/base';

// components
import SettlementAuditFilter from './auditFilter';
import CommissionAuditDialog from './auditDialog';
import GameCommissionDialog from './gameCommissionDialog';
import ApportionCommissionDialog from './apportionCommissionDialog';
import AdjustCommissionDialog from './adjustCommissionDialog';
import CommissionAuditViewDialog from './auditViewDialog';
import SubCommissionDialog from './subCommissionDialog';
import MultiplyAuditDialog from './multiplyAuditDialog';
import NextMemberCommissionDialog from './nextMemberCommissionDialog';
import AddPointsRebate from './addPointsRebate';

// service
import {
  getCommissionAudits,
  // getCommissionAuditsExport,
  getCommissionSelect,
  getCommissionCaseSelectList,
} from '@/services/api/commission';

// mixins
import { grid, dialog } from '@/build';

const headerMap = {
  settleDate: '结算月份',
  username: '代理账号',
  name: '姓名',
  userStatus: '账号状态',
  formatFeeRule: '手续费方案(本月)',
  formatCommName: '佣金方案类型',
  formatCashRule: '会员反佣方案(现金网)',
  userCount: '有效会员',
  proxyCount: '有效下级代理总数',
  formatWinTotal: '公司总输赢',
  formatCost: '成本总计',
  formatLastAmount: '累加上月',
  formatCommAmount: '下级会员佣金',
  formatProxyComm: '下级代理佣金',
  // formatUpAmountRet: '上分返利',
  formatAmount: '实际合计发放',
  status: '结算状态',
  firstTime: '时间',
  firstApprover: '审核人',
};

export default {
  name: 'commission-settlement-audit',
  components: {
    CommissionAuditViewDialog,
    AdjustCommissionDialog,
    SubCommissionDialog,
    NextMemberCommissionDialog,
    ApportionCommissionDialog,
    GameCommissionDialog,
    CommissionAuditDialog,
    SettlementAuditFilter,
    MultiplyAuditDialog,
    AddPointsRebate,
  },
  mixins: [grid, dialog],
  data() {
    return {
      tableData: {},
      ids: [],
      filters: {
        size: 20,
        page: 1,
        searchType: 1,
        settleDate: moment().format('YYYY-MM'),
      },
      auditStep: 0,
      dialogVisible: false,
      staticDialogName: 'commission-audit-dialog',
      staticDialogName2: 'game-commission-dialog',
      staticDialogName3: 'apportion-commission-dialog',
      staticDialogName4: 'adjust-commission-dialog',
      staticDialogName5: 'commission-audit-view-dialog',
      staticDialogName6: 'sub-commission-dialogg',
      staticDialogName7: 'mul-commission-audit-dialog',
      staticDialogName8: 'next-member-commission-dialog',
      staticDialogName9: 'add-points-rebate',
      commSeleList: [],
      commCaseSeleList: [],
    };
  },
  computed: {
    idsArr() {
      return this.ids.map(item => item.id);
    },
  },
  methods: {
    formatCommMode,
    formatFeeRuleName(row) {
      if (!this.commSeleList.length) return null;
      const { name } = this.commSeleList.find(item => item.id === row.feeRule) || {};
      return name;
    },
    formatCashRuleName(row) {
      if (!this.commCaseSeleList.length) return null;
      const { name } = this.commCaseSeleList.find(item => item.id === row.cashRule) || {};
      return name;
    },
    isSelectable(row, index) {
      return !_.includes([2, 3, 4], row.status);
    },
    showAuditDialog(row, step) {
      this.auditStep = step;
      // 初审备注
      this.firstRemark = row.firstRemark;
      this.openDialog({ props: row, dialogName: this.staticDialogName });
    },
    submitFilterForm(formInline) {
      this.formatData(formInline);
      this.gridSearch();
    },
    // 表格前面的checkbox操作
    handleSelectionChange(val) {
      this.ids = val;
    },
    multipAudit() {
      if (this.idsArr.length <= 0) {
        this.$message({
          type: 'warning',
          message: '请勾选数据',
        });
        return;
      }
      this.openDialog({ dialogName: this.staticDialogName7 });
    },
    setStep(step) {
      this.auditStep = step;
    },
    // 导出
    async exportHandle(formInline) {
      try {
        this.downloadLoading = true;
        this.formatData(formInline);
        const [status, result] = await getCommissionAudits(this.filters);
        if (!status) throw new Error(result.message);
        const filename = '佣金结算报表.csv';
        const header = mapToArray(headerMap);
        const filterField = Object.keys(headerMap);
        const exportData = this.formatList(result.list);
        this.export2Excel(header, filterField, exportData, filename);
      } catch (e) {
        this.$message({
          message: `${e.message || ''}`,
          type: 'error',
        });
      } finally {
        this.downloadLoading = false;
      }
    },
    formatList(list) {
      return list.map(item => ({
        ...item,
        formatFeeRule: this.formatFeeRuleName(item),
        formatCommName: this.formatCommMode(item.commMode).name,
        formatCashRule: item.commMode == 1 ? this.formatCashRuleName(item) : '--',
        formatWinTotal: _.currency(item.winTotal),
        formatCost: _.currency(item.cost),
        formatLastAmount: _.currency(item.lastAmount),
        formatCommAmount: _.currency(item.commAmount),
        formatProxyComm: _.currency(item.proxyComm),
        formatUpAmountRet: _.currency(item.upAmountRet),
        formatAmount: _.currency(item.amount),
        status: agencyEnum.AUDIT_REVIEW_TYPE[item.status],
        userStatus: agencyEnum.COMMISSION_ACCOUNT_STATUS[item.userStatus],
        firstTime: _.toTime(item.firstTime),
      }));
    },
    formatData(formInline) {
      this.filters = { ...this.filters, ...formInline };
    },
  },
  mounted() {
    this.bindGet(getCommissionSelect, 'commSeleList', {
      format: (data) => {
        if (!(Array.isArray(data) && data.length)) return [];
        data.unshift(FILTER_ALL_TYPE);
        return data;
      },
    });
    this.bindGet(getCommissionCaseSelectList, 'commCaseSeleList', {
      format: (data) => {
        if (!(Array.isArray(data) && data.length)) return [];
        data.unshift(FILTER_ALL_TYPE);
        return data;
      },
    });
    this.bindGet(getCommissionAudits, 'tableData', {
      action: 'getGrid',
      sendingData: 'filters',
    });
    this.getAll();
  },
};
</script>

<style scoped>
</style>
